﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 库位表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class BinlocationService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Binlocation> _binlocationRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public BinlocationService(SqlSugarRepository<Binlocation> binlocationRep, ISqlSugarClient sqlSugarClient)
    {
        _binlocationRep = binlocationRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询库位表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询库位表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<BinlocationOutput>> Page(PageBinlocationInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _binlocationRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.BinlocationCode.Contains(input.Keyword) || u.BinlocationName.Contains(input.Keyword) || u.Capacity.Contains(input.Keyword) || u.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.BinlocationCode), u => u.BinlocationCode.Contains(input.BinlocationCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.BinlocationName), u => u.BinlocationName.Contains(input.BinlocationName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Capacity), u => u.Capacity.Contains(input.Capacity.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.OrganizationId != null, u => u.OrganizationId == input.OrganizationId)
            .WhereIF(input.Sort != null, u => u.Sort == input.Sort)
            .WhereIF(input.RepositoryID != null, u => u.RepositoryID == input.RepositoryID)
            .LeftJoin<UserManagement>((u, organization) => u.OrganizationId == organization.Id)
            .LeftJoin<Warehouse>((u, organization, repository) => u.RepositoryID == repository.Id)
            .Select((u, organization, repository) => new BinlocationOutput
            {
                Id = u.Id,
                BinlocationCode = u.BinlocationCode,
                BinlocationName = u.BinlocationName,
                Capacity = u.Capacity,
                OrganizationId = u.OrganizationId,
                OrganizationFkDisplayName = $"{organization.UserName}",
                Sort = u.Sort,
                State = u.State,
                Remark = u.Remark,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                RepositoryID = u.RepositoryID,
                RepositoryFkDisplayName = $"{repository.WarehouseName}",
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取库位表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取库位表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Binlocation> Detail([FromQuery] QueryByIdBinlocationInput input)
    {
        return await _binlocationRep.GetFirstAsync(u => u.Id == input.Id);
    }


    

    /// <summary>
    /// 增加库位表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加库位表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddBinlocationInput input)
    {
        var entity = input.Adapt<Binlocation>();
        return await _binlocationRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新库位表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新库位表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateBinlocationInput input)
    {
        var entity = input.Adapt<Binlocation>();
        await _binlocationRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除库位表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除库位表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteBinlocationInput input)
    {
        var entity = await _binlocationRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _binlocationRep.FakeDeleteAsync(entity);   //假删除
        //await _binlocationRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除库位表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除库位表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteBinlocationInput> input)
    {
        var exp = Expressionable.Create<Binlocation>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _binlocationRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _binlocationRep.FakeDeleteAsync(list);   //假删除
        //return await _binlocationRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataBinlocationInput input)
    {
        var organizationIdData = await _binlocationRep.Context.Queryable<UserManagement>()
            .InnerJoinIF<Binlocation>(input.FromPage, (u, r) => u.Id == r.OrganizationId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        var repositoryIDData = await _binlocationRep.Context.Queryable<Warehouse>()
            .InnerJoinIF<Binlocation>(input.FromPage, (u, r) => u.Id == r.RepositoryID)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.WarehouseName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "organizationId", organizationIdData },
            { "repositoryID", repositoryIDData },
        };
    }
    
    /// <summary>
    /// 导出库位表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出库位表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageBinlocationInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportBinlocationOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "库位表导出记录");
    }
    
    /// <summary>
    /// 下载库位表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载库位表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportBinlocationOutput>(), "库位表导入模板", (_, info) =>
        {
            if (nameof(ExportBinlocationOutput.OrganizationFkDisplayName) == info.Name) return _binlocationRep.Context.Queryable<UserManagement>().Select(u => $"{u.UserName}").Distinct().ToList();
            if (nameof(ExportBinlocationOutput.RepositoryFkDisplayName) == info.Name) return _binlocationRep.Context.Queryable<Warehouse>().Select(u => $"{u.WarehouseName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入库位表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入库位表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportBinlocationInput, Binlocation>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 库位主管
                    var organizationIdLabelList = pageItems.Where(x => x.OrganizationFkDisplayName != null).Select(x => x.OrganizationFkDisplayName).Distinct().ToList();
                    if (organizationIdLabelList.Any()) {
                        var organizationIdLinkMap = _binlocationRep.Context.Queryable<UserManagement>().Where(u => organizationIdLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.OrganizationId = organizationIdLinkMap.GetValueOrDefault(e.OrganizationFkDisplayName ?? "");
                            if (e.OrganizationId == null) e.Error = "库位主管链接失败";
                        });
                    }
                    // 链接 仓库ID
                    var repositoryIDLabelList = pageItems.Where(x => x.RepositoryFkDisplayName != null).Select(x => x.RepositoryFkDisplayName).Distinct().ToList();
                    if (repositoryIDLabelList.Any()) {
                        var repositoryIDLinkMap = _binlocationRep.Context.Queryable<Warehouse>().Where(u => repositoryIDLabelList.Contains($"{u.WarehouseName}")).ToList().ToDictionary(u => $"{u.WarehouseName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.RepositoryID = repositoryIDLinkMap.GetValueOrDefault(e.RepositoryFkDisplayName ?? "");
                            if (e.RepositoryID == null) e.Error = "仓库ID链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.RepositoryID == null){
                            x.Error = "仓库ID不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Binlocation>>();
                    
                    var storageable = _binlocationRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.BinlocationCode?.Length > 50, "库位编号长度不能超过50个字符")
                        .SplitError(it => it.Item.BinlocationName?.Length > 50, "库位名称长度不能超过50个字符")
                        .SplitError(it => it.Item.Capacity?.Length > 32, "库位容量/m³长度不能超过32个字符")
                        .SplitError(it => it.Item.Remark?.Length > 300, "备注长度不能超过300个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
